package com.example.CarManagement.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.CarManagement.common.Result;
import com.example.CarManagement.sys.entity.*;
import com.example.CarManagement.sys.mapper.CarInfoMapper;
import com.example.CarManagement.sys.mapper.DriversMapper;
import com.example.CarManagement.sys.mapper.OrdersMapper;
import com.example.CarManagement.sys.mapper.UserMapper;
import com.example.CarManagement.sys.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单表，记录派车信息和实际用车情况 服务实现类
 * </p>
 *
 * @author 徐佳彪
 * @since 2025-07-23
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {


    @Resource
    private UserMapper userMapper;


    @Resource
    private CarInfoMapper carInfoMapper;


    @Resource
    private DriversMapper driversMapper;


    @Override
    public Result<?> getPageList(Integer pageNo, Integer pageSize, String applicationId, String orderNumber) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

        if (applicationId != null) {
            queryWrapper.like(Orders::getApplicationId, applicationId);
        }
        if (orderNumber != null) {
            queryWrapper.eq(Orders::getOrderNumber, orderNumber);
        }

        Page<Orders> ordersPage = this.baseMapper.selectPage(new Page<>(pageNo, pageSize), queryWrapper);

        // 角色总数
        Integer total = (int) ordersPage.getTotal();


        List<Orders> applications = ordersPage.getRecords();

        Map<String, Object> data = new HashMap<>();
        data.put("rows", applications);
        data.put("total", total);

        return Result.success(data);
    }

    @Override
    public Result<?> orderInfo(String id) {
        Orders orders = this.baseMapper.selectById(id);

        // 查询用户名称
        String dispatcherId = orders.getDispatcherId();
        User user = userMapper.selectById(dispatcherId);

        // 车辆名称
        CarInfo carInfo = carInfoMapper.selectById(orders.getVehicleId());

        // 司机司机名称
        LambdaQueryWrapper<Drivers> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Drivers::getDriverId, orders.getDriverId());
        Drivers drivers = driversMapper.selectOne(queryWrapper);
        User driverUser = userMapper.selectById(drivers.getUserId());

        Map<String, Object> data = new HashMap<>();

        data.put("order", orders);
        data.put("username", user.getUsername());
        data.put("plateNumber", carInfo.getPlateNumber());
        data.put("driversName", driverUser.getUsername());

        return Result.success(data);
    }
}
